package cn.itcast.service.system.impl;

import cn.itcast.dao.dept.RoleDao;
import cn.itcast.domain.system.Role;
import cn.itcast.service.system.RoleService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.UUID;

@Service
public class RoleServiceImpl implements RoleService {
    @Autowired
    private RoleDao roleDao;
    @Override
    public Role findById(String id) {
        return roleDao.findById(id);
    }

    @Override
    public PageInfo<Role> findByPage(String companyId, int pageNum, int pageSize) {
        //1.开启分页设置从第一页开始
        PageHelper.startPage(pageNum,pageSize);
        //2.调用dao
        List<Role> list = roleDao.findAll(companyId);
        return new PageInfo<>(list);
    }
//删除
    @Override
    public String delete(String id) {
        long count=roleDao.findUserRole(id);
        long count2=roleDao.findRole(id);
        if (count>0 || count2>0){

         return "0";
        }
        roleDao.delete(id);
        return "1";
    }

    //添加
    @Override
    public void save(Role role) {
        //设置id
        role.setId(UUID.randomUUID().toString());
roleDao.save(role);
    }

    //修改
    @Override
    public void update(Role role) {
    roleDao.update(role);
    }


    //查询所有角色
    @Override
    public List<Role> findAll(String id) {
        return roleDao.findAll(id);
    }
//查询用户已经拥有的角色
    @Override
    public List<Role> findRoleByUserId(String id) {
        return roleDao.findRoleByUserId(id);
    }

    @Override
    public void updateRoleModule(String roleId, String moduleIds) {
        //1.删除角色权限，根据角色id
        roleDao.deleteRoleModuleByRoleId(roleId);
        //2.角色添加权限
        if (!StringUtils.isEmpty(moduleIds)){
            String[] array = moduleIds.split(",");
            if (array!=null&&array.length>0){
                for (String moduleId : array) {
                    roleDao.saveRoleModeule(roleId,moduleId);
                }
            }
        }

    }
}
